package com.cangxuan.app.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.ByteArrayOutputStream;

public class BitmapUtils {

    private static final String TAG = "BitmapSizeUtils";

    /**
     * 获取指定尺寸于鏊求的 Bitmap 对象
     * 该方法有缺陷 , 计算值的时候没有考虑像素密度
     * 如果从不同像素密度的资源文件中加载
     * 可能计算出的值与指定的 maxBitmapWidth maxBitmapHeight 略有出入
     *
     * @param context           上下文对象
     * @param maxBitmapWidth    Bitmap 的最大宽度
     * @param maxBitmapHeight   Bitmap 的最大高度
     * @param hasAlphaChannel   是否包含 ALPHA 通道, 即透明度信息
     * @param inBitmap          复用的 Bitmap, 将新的 Bitmap 对象解析到该 Bitmap 内存中
     * @return  返回新的 Bitmap 对象
     */
    public static Bitmap getResizedBitmap(Context context,
                                          String filePath, int maxBitmapWidth, int maxBitmapHeight,
                                          boolean hasAlphaChannel){
        BitmapFactory.Options options = new BitmapFactory.Options();
        int imageWidth;
        int imageHeight;
        int inSampleSize = 1;
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        imageWidth = options.outWidth;
        imageHeight = options.outHeight;
        if(imageWidth > maxBitmapWidth || imageHeight > maxBitmapHeight){
            while ( imageWidth / inSampleSize > maxBitmapWidth ||
                    imageHeight / inSampleSize > maxBitmapHeight ){
                inSampleSize = inSampleSize * 2;
            }
            Log.w(TAG, "getResizedBitmap inSampleSize=" + inSampleSize);
        }
        options.inSampleSize = inSampleSize;
        if (!hasAlphaChannel){
            options.inPreferredConfig = Bitmap.Config.RGB_565;
        }
        options.inJustDecodeBounds = false;
        options.inMutable = true;
        return BitmapFactory.decodeFile(filePath, options);
    }

    public static Bitmap convert(String base64Str) throws IllegalArgumentException
    {
        byte[] decodedBytes = java.util.Base64.getDecoder().decode(
                base64Str.substring(base64Str.indexOf(",")  + 1));
        return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
    }

    public static String convert(Bitmap bitmap)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        return java.util.Base64.getEncoder().encodeToString(outputStream.toByteArray());
    }


}
